package top.malaoshi.webmvc;

import top.malaoshi.util.io.TextFileReader;
import top.malaoshi.util.io.Resources;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局变量
 */
public class GlobalVariable {

    public static String errorHtml;
    private static GlobalVariable me = new GlobalVariable();
    private Map<String,Object> map = new HashMap<>();
    private GlobalVariable(){
        readErrorHtml();
    }
    public static GlobalVariable me(){
        return me;
    }
    public void put(String key,Object value){
        map.put(key, value);
    }
    public Object get(String key){
        return map.get(key);
    }
    /**
     * 读取 error.html
     */
    private void readErrorHtml(){
        TextFileReader tfr = null;
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("/error.html");
            tfr = new TextFileReader(is,"UTF-8");
            errorHtml = tfr.readText();
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if(tfr!=null) {
                try {
                    tfr.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
